﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChatForum.Business.Contract;
using ChatForum.DAL;
using ChatForum.Application.Service;
using ChatForum.Database;
using ChatForum.Messaging;
using System.Collections.Specialized;
using System.Configuration;

namespace ServiceHelper
{
    public class ServiceHelper
    {
        private static ServiceHelper instance;
        private static object _lock = new object();
        private ServiceHelper() { Init(); }
        private static ServiceHelper GetInstance()
        {
            lock (_lock)
            {
                if (instance == null)
                    instance = new ServiceHelper();
            }
            return instance;
        }

        private DatabaseBase database = null;
        private IRepository repository = null;
		private SmtpServerBase smtpServer = null;
        public IAccountService accountService = null;
        public IForumService forumService = null;

        private void Init()
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            string dataSource = appSettings["dataSource"];
            string databaseName = appSettings["databaseName"];
            string userId = appSettings["userId"];
            string password = appSettings["password"];
            string smtpHost = appSettings["smtpHost"];
            int smtpPort = Int32.TryParse(appSettings["smtpPort"], out smtpPort) ? smtpPort : 587;
            string smtpUserId = appSettings["smtpUserId"];
            string smtpPassword = appSettings["smtpPassword"];

            database = new SqlServerDatabase(dataSource, databaseName, userId, password, null);
            repository = new ChatForumRepository(database);
            smtpServer = new SmtpServerBase(smtpHost, smtpPort, smtpUserId, smtpPassword);
            accountService = new AccountService(repository, smtpServer);
            forumService = new ForumService(repository);
        }

        public static IAccountService AccountService
        {
            get { return GetInstance().accountService; }
        }
        public static IForumService ForumService
        {
            get { return GetInstance().forumService; }
        }
    }
}
